//
//  SLMineViewController.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/21.
//


#import "SLMineViewController.h"
#import <YYKit.h>
#import <Masonry.h>

@interface SLMineCell : UITableViewCell
@property (nonatomic, strong) UIStackView *stackView;
@property (nonatomic, strong) NSArray *data;
@property (nonatomic, copy  ) void(^itemClickCallback)(NSInteger index);
@end
@implementation SLMineCell


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.stackView];
        [self.stackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.contentView).inset(20);
            make.top.bottom.equalTo(self.contentView).inset(18);
        }];
    }
    return self;
}
- (void)setData:(NSArray *)data {
    _data = data;
    [self.stackView removeAllSubviews];
    for (NSDictionary *dict in data) {
        UIView *item = [UIView new];
        @weakify(self);
        [item jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            !self.itemClickCallback ?: self.itemClickCallback([data indexOfObject:dict]);
        }];
        [self.stackView addArrangedSubview:item];
        
        UIImageView *icon = [UIImageView new];
        icon.image = [UIImage imageNamed:dict[@"image"]];
        [item addSubview:icon];
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(icon.superview);
            make.height.mas_equalTo(aspectValue(84));
        }];
        
        UILabel *title = [UILabel new];
        title.text = dict[@"title"];
        title.numberOfLines = 0;
        title.font = aspectDefaultFont(14);
        title.textAlignment = NSTextAlignmentCenter;
        [item addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(title.superview);
            make.top.equalTo(icon.mas_bottom).offset(10);
        }];
    }
}
- (UIStackView *)stackView {
    if (!_stackView) {
        _stackView = [UIStackView new];
        _stackView.spacing = 10;
        _stackView.distribution = UIStackViewDistributionFillEqually;
    }
    return _stackView;
}
@end



@interface SLMineViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *data;

@end

@implementation SLMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = UIColorHex(#1B1B1B);
    
    self.data = @[
        @{
            @"image": @"icon_mine_order",
            @"title": @"Order In Progress",
        },
        @{
            @"image": @"icon_mine_loan_agreement",
            @"title": @"Loan Agreement",
        },
        @[
            @{
                @"image": @"icon_obtain_communication",
                @"title": @"Obtain Communication",
            },
            @{
                @"image": @"icon_official_platform",
                @"title": @"Official Platform",
            },
            @{
                @"image": @"icon_setting",
                @"title": @"Settings",
            }
        ]
    ].mutableCopy;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(0);
        make.top.equalTo(self.view).inset(SAFE_AREA_INSETS.top);
        make.bottom.equalTo(self.view).inset(0);
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"UITableViewHeaderFooterView"];
    header.backgroundColor = UIColor.clearColor;
    header.contentView.backgroundColor = UIColorHex(#1B1B1B);
    UIView *bgView = [header viewWithTag:1000];
    if (!bgView) {
        bgView = [UIView new];
        bgView.tag = 1000;
        bgView.backgroundColor = UIColor.whiteColor;
        [header addSubview:bgView];
        [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(header);
        }];
    }
    
    UIImageView *iv = [header viewWithTag:1001];
    if (!iv) {
        iv = [UIImageView new];
        iv.tag = 1001;
        iv.image = [UIImage imageNamed:@"icon_circle_bar"];
        iv.contentMode = UIViewContentModeScaleAspectFit;
        [header addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(header).inset(20);
            make.top.bottom.equalTo(header).inset(10);
        }];
    }
    
    return header;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header layoutIfNeeded];
    UIView *bgView = [header viewWithTag:1000];
    [bgView roundTopCornerRadius:20];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.data[indexPath.row] isKindOfClass:NSDictionary.class]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        cell.imageView.image = [UIImage imageNamed:self.data[indexPath.row][@"image"]]; //[UIImage imageNamed:@"icon_mine_loan_agreement"];
        cell.textLabel.text = self.data[indexPath.row][@"title"];
        cell.backgroundColor = UIColor.clearColor;
        cell.contentView.backgroundColor = UIColor.whiteColor;
        UIView *accessory = [UIView new];
        accessory.frame = CGRectMake(0, 0, 40, 40);
        UIImageView *iv = [UIImageView new];
        iv.image = [UIImage imageNamed:@"btn_more_pink"];
        iv.contentMode = UIViewContentModeScaleAspectFit;
        [accessory addSubview:iv];
        [iv mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(accessory);
            make.width.height.mas_equalTo(22);
        }];
        cell.accessoryView = accessory;
        return cell;
    } else if ([self.data[indexPath.row] isKindOfClass:NSArray.class]){
        SLMineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLMineCell" forIndexPath:indexPath];
        
        cell.data = self.data[indexPath.row];
        cell.itemClickCallback = ^(NSInteger index) {
            if (index == 0) {
                [SLRoutePush route:Configuration.ContactUsDomain parameter:nil];
            } else if (index == 1) {
                [SLRoutePush route:Configuration.AboutOurDomain parameter:nil];
            } else if (index == 2) {
                [SLRoutePush route:@"SLSettingsViewController" parameter:nil];
            }
        };
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.data[indexPath.row]isKindOfClass:NSDictionary.class] ? aspectValue(59) : UITableViewAutomaticDimension; // aspectValue(120);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id obj = self.data[indexPath.row];
    if ([obj isKindOfClass:NSDictionary.class]) {
        NSDictionary *dict = (NSDictionary *)obj;
        if ([dict[@"title"] isEqualToString:@"Order In Progress"]) {
            [SLRoutePush route:@"SLOrderListContainerViewController" parameter:nil];
        } else if ([dict[@"title"] isEqualToString:@"Loan Agreement"]) {
            [SLRoutePush route:Configuration.LoanAgreementDomain parameter:nil];
        }
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:UITableViewHeaderFooterView.class forHeaderFooterViewReuseIdentifier:@"UITableViewHeaderFooterView"];
        [_tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"UITableViewCell"];
        [_tableView registerClass:SLMineCell.class forCellReuseIdentifier:@"SLMineCell"];
        _tableView.tableHeaderView = [self tableHeaderView];
        _tableView.tableFooterView = [self tableFooterView];
    }
    return _tableView;
}
- (UIView *)tableHeaderView {
    UIView *head = [UIView new];
    head.backgroundColor = UIColorHex(#1B1B1B);
    head.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 300);
    
    UILabel *title = [UILabel new];
    title.text = @"SultitLoan";
    title.textColor = UIColor.whiteColor;
    title.font = aspectDefaultFont(18);
    [head addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head).inset(20);
        make.top.equalTo(head).offset(30);
    }];
    
    UIImageView *iv = [UIImageView new];
    iv.contentMode = UIViewContentModeScaleAspectFit;
    iv.image = [UIImage imageNamed:@"icon_mine_avatar"];
    [head addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.height.mas_equalTo(160);
        make.centerX.equalTo(head);
    }];
    
    UILabel *name = [UILabel new];
    name.text = User.user.phone;
    if (User.user.phone.length > 8) {
        NSRange range = NSMakeRange(User.user.phone.length-8, 4);
        NSString *showPhone = [User.user.phone stringByReplacingCharactersInRange:range withString:@"****"];
        name.text = showPhone;
    }
    name.textColor = UIColor.whiteColor;
    name.textAlignment = NSTextAlignmentCenter;
    name.font = aspectDefaultFont(14);
    [head addSubview:name];
    [name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(head);
        make.top.equalTo(iv.mas_bottom).offset(20);
        make.bottom.equalTo(head).inset(20);
    }];
    
    return head;
}


- (UIView *)tableFooterView {
    UIView *foot = [UIView new];
    foot.backgroundColor = UIColor.whiteColor;
    foot.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 115);
    
    UIButton *signOut = [UIButton buttonWithType:UIButtonTypeCustom];
    [signOut setTitle:@"Sign Out" forState:UIControlStateNormal];
    [signOut setImage:[UIImage imageNamed:@"btn_more_white"] forState:UIControlStateNormal];
    [signOut jk_setImagePosition:LXMImagePositionRight spacing:10];
    [signOut setTitleColor:UIColorHex(#1B1B1B) forState:UIControlStateNormal];
    signOut.layer.cornerRadius = 24;
    signOut.layer.borderColor = UIColorHex(#1B1B1B).CGColor;
    signOut.layer.borderWidth = 1.8;
    signOut.backgroundColor = UIColorHex(#FDC5E0);
    [signOut addTarget:self action:@selector(signOutButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [foot addSubview:signOut];
    [signOut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(foot);
        make.top.equalTo(foot).offset(23);
        make.width.mas_equalTo(signOut.intrinsicContentSize.width+85*2);
        make.height.mas_equalTo(54);
    }];
    
    return foot;
}



#pragma mark 点击事件
- (void)signOutButtonAction:(UIButton *)button {
    [SLAlertView signOutAlertWithLeftCallback:^(UIButton * _Nonnull button) {
        [LogoutRequestProvider requestLogoutWithSuccess:^(BOOL success) {
            [SLRoutePush rootRoute:@"SLLoginViewController"];
        } failure:^(YTKRequest * _Nonnull request) {
            [ResponseToast showToastWithRequest:request];
        }];
    } rightCallback:^(UIButton * _Nonnull button) {
        
    }];
}
@end
